<template>
  <a-layout class="cases-layout">
    <AppHeader activeKey="cases" @logout="handleLogout" />

    <a-layout-content class="content">
      <div class="page-header">
        <div class="page-title">
          <h2>病例管理</h2>
        </div>
        <div class="page-actions">
          <a-button type="primary" @click="showNewCaseModal">
            <template #icon><PlusOutlined /></template>
            新建病例
          </a-button>
        </div>
      </div>

      <div class="page-content">
        <div class="search-bar">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-input-search
                v-model:value="searchForm.keyword"
                placeholder="搜索患者姓名/手机号"
                @search="handleSearch"
              />
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.status"
                placeholder="病例状态"
                style="width: 100%"
                @change="handleSearch"
              >
                <a-select-option value="">全部状态</a-select-option>
                <a-select-option value="initial">初诊</a-select-option>
                <a-select-option value="in_treatment">治疗中</a-select-option>
                <a-select-option value="completed">治疗完成</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-range-picker
                v-model:value="searchForm.dateRange"
                style="width: 100%"
                @change="handleSearch"
              />
            </a-col>
            <a-col :span="6">
              <a-input-search
                v-model:value="searchForm.archiveId"
                placeholder="搜索档案号"
                @search="handleSearch"
              />
            </a-col>
          </a-row>
        </div>

        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #status="{ text }">
            <a-tag :color="getStatusColor(text)">
              {{ getStatusText(text) }}
            </a-tag>
          </template>

          <template #action="{ record }">
            <a-space>
              <a @click="viewCase(record)">查看</a>
              <a @click="editCase(record)">编辑</a>
              <a-popconfirm
                title="确定要删除这个病例吗？"
                @confirm="deleteCase(record)"
              >
                <a class="danger-link">删除</a>
              </a-popconfirm>
            </a-space>
          </template>

          <template #nextVisit="{ text }">
            {{ text || '无安排' }}
          </template>
        </a-table>
      </div>
    </a-layout-content>

    <!-- 新建/编辑病例弹窗 -->
    <a-modal
      v-model:visible="caseModalVisible"
      :title="modalTitle"
      width="800px"
      :footer="null"
    >
      <new-case-form
        :case-data="currentCase"
        @submit="handleCaseSubmit"
        @cancel="caseModalVisible = false"
      />
    </a-modal>

    <!-- 病例详情弹窗 -->
    <a-modal
      v-model:visible="caseDetailVisible"
      title="病例详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedCase" class="case-detail">
        <div class="detail-header">
          <div class="patient-info">
            <h3>{{ selectedCase.patientName }} <a-tag>{{ selectedCase.gender }}</a-tag> <span>{{ selectedCase.age }}岁</span></h3>
            <div class="archive-id">档案号：{{ selectedCase.archiveId }}</div>
          </div>
          <div class="detail-actions">
            <a-button type="primary" @click="handleEditFromDetail">
              <template #icon><EditOutlined /></template>
              编辑病例
            </a-button>
          </div>
        </div>

        <a-tabs default-active-key="basic">
          <a-tab-pane key="basic" tab="基本信息">
            <a-descriptions bordered :column="2">
              <a-descriptions-item label="患者姓名" span="1">{{ selectedCase.patientName }}</a-descriptions-item>
              <a-descriptions-item label="性别" span="1">{{ selectedCase.gender }}</a-descriptions-item>
              <a-descriptions-item label="年龄" span="1">{{ selectedCase.age }}</a-descriptions-item>
              <a-descriptions-item label="联系电话" span="1">{{ selectedCase.phone }}</a-descriptions-item>
              <a-descriptions-item label="档案号" span="1">{{ selectedCase.archiveId }}</a-descriptions-item>
              <a-descriptions-item label="主治医生" span="1">{{ selectedCase.doctor }}</a-descriptions-item>
              <a-descriptions-item label="状态" span="1">
                <a-tag :color="getStatusColor(selectedCase.status)">
                  {{ getStatusText(selectedCase.status) }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="创建时间" span="1">{{ selectedCase.createTime }}</a-descriptions-item>
              <a-descriptions-item label="最近就诊" span="1">{{ selectedCase.lastVisit }}</a-descriptions-item>
              <a-descriptions-item label="下次就诊" span="1">{{ selectedCase.nextVisit || '无安排' }}</a-descriptions-item>
              <a-descriptions-item label="诊断" span="2">{{ selectedCase.diagnosis }}</a-descriptions-item>
              <a-descriptions-item label="治疗方案" span="2">{{ selectedCase.treatment }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          
          <a-tab-pane key="records" tab="就诊记录">
            <div class="visit-records">
              <a-timeline>
                <a-timeline-item v-for="(record, index) in visitRecords" :key="index">
                  <div class="visit-record">
                    <div class="visit-date">{{ record.date }}</div>
                    <div class="visit-doctor">医生：{{ record.doctor }}</div>
                    <div class="visit-content">{{ record.content }}</div>
                  </div>
                </a-timeline-item>
              </a-timeline>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="images" tab="影像资料">
            <div class="image-gallery">
              <div v-for="(image, index) in caseImages" :key="index" class="image-item">
                <img :src="image.url" :alt="image.description" />
                <div class="image-description">{{ image.description }}</div>
                <div class="image-date">{{ image.date }}</div>
              </div>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="prescriptions" tab="处方记录">
            <a-collapse>
              <a-collapse-panel v-for="(prescription, index) in prescriptions" :key="index" :header="prescription.date + ' 处方'">
                <div class="prescription-detail">
                  <div class="prescription-doctor">开方医生：{{ prescription.doctor }}</div>
                  <div class="prescription-items">
                    <div v-for="(item, idx) in prescription.items" :key="idx" class="prescription-item">
                      <div class="item-name">{{ item.name }}</div>
                      <div class="item-dosage">{{ item.dosage }}</div>
                      <div class="item-usage">{{ item.usage }}</div>
                    </div>
                  </div>
                  <div class="prescription-notes">备注：{{ prescription.notes }}</div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>
  </a-layout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { 
  UserOutlined,
  PlusOutlined,
  EditOutlined
} from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import NewCaseForm from '../components/NewCaseForm.vue'
import AppHeader from '../components/AppHeader.vue'

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: null,
  archiveId: ''
})

// 表格列定义
const columns = [
  {
    title: '患者姓名',
    dataIndex: 'patientName',
    key: 'patientName',
    width: 100
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 60
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    width: 60
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 120
  },
  {
    title: '档案号',
    dataIndex: 'archiveId',
    key: 'archiveId',
    width: 120
  },
  {
    title: '主治医生',
    dataIndex: 'doctor',
    key: 'doctor',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 90,
    slots: { customRender: 'status' }
  },
  {
    title: '最近就诊',
    dataIndex: 'lastVisit',
    key: 'lastVisit',
    width: 100
  },
  {
    title: '下次就诊',
    dataIndex: 'nextVisit',
    key: 'nextVisit',
    width: 100,
    slots: { customRender: 'nextVisit' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 180,
    slots: { customRender: 'action' }
  }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
})

// 病例弹窗相关
const caseModalVisible = ref(false)
const modalTitle = ref('新建病例')
const currentCase = ref(null)

// 病例详情弹窗相关
const caseDetailVisible = ref(false)
const selectedCase = ref(null)

// 模拟就诊记录数据
const visitRecords = ref([])

// 模拟影像资料
const caseImages = ref([])

// 模拟处方记录
const prescriptions = ref([])

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    initial: 'blue',
    in_treatment: 'orange',
    completed: 'green'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    initial: '初诊',
    in_treatment: '治疗中',
    completed: '治疗完成'
  }
  return textMap[status] || '未知'
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchTableData()
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTableData()
}

// 获取表格数据
const fetchTableData = () => {
  loading.value = true
  // 模拟接口调用
  setTimeout(() => {
    // 创建原始数据
    const allData = [
      {
        id: 1,
        patientName: '张三',
        gender: '男',
        age: 25,
        phone: '13800138000',
        doctor: '李医生',
        status: 'initial',
        archiveId: 'A20240115001',
        lastVisit: '2024-01-15',
        nextVisit: '2024-02-15',
        diagnosis: '牙齿矫正',
        treatment: '隐形矫正器',
        createTime: '2024-01-15 10:00:00'
      },
      {
        id: 2,
        patientName: '李四',
        gender: '男',
        age: 32,
        phone: '13900139000',
        doctor: '王医生',
        status: 'in_treatment',
        archiveId: 'A20240120002',
        lastVisit: '2024-02-20',
        nextVisit: '2024-03-20',
        diagnosis: '牙周炎',
        treatment: '牙周治疗',
        createTime: '2024-01-20 14:30:00'
      },
      {
        id: 3,
        patientName: '王五',
        gender: '男',
        age: 45,
        phone: '13700137000',
        doctor: '张医生',
        status: 'completed',
        archiveId: 'A20240125003',
        lastVisit: '2024-02-25',
        nextVisit: null,
        diagnosis: '龋齿',
        treatment: '补牙治疗',
        createTime: '2024-01-25 09:15:00'
      },
      {
        id: 4,
        patientName: '赵六',
        gender: '女',
        age: 28,
        phone: '13600136000',
        doctor: '李医生',
        status: 'initial',
        archiveId: 'A20240201004',
        lastVisit: '2024-02-01',
        nextVisit: '2024-03-01',
        diagnosis: '牙齿敏感',
        treatment: '脱敏治疗',
        createTime: '2024-02-01 11:20:00'
      },
      {
        id: 5,
        patientName: '钱七',
        gender: '女',
        age: 35,
        phone: '13500135000',
        doctor: '王医生',
        status: 'in_treatment',
        archiveId: 'A20240205005',
        lastVisit: '2024-03-05',
        nextVisit: '2024-04-05',
        diagnosis: '牙齿缺失',
        treatment: '种植牙',
        createTime: '2024-02-05 16:45:00'
      },
      {
        id: 6,
        patientName: '孙八',
        gender: '男',
        age: 52,
        phone: '13400134000',
        doctor: '张医生',
        status: 'completed',
        archiveId: 'A20240210006',
        lastVisit: '2024-03-10',
        nextVisit: null,
        diagnosis: '牙齿美白',
        treatment: '美白治疗',
        createTime: '2024-02-10 13:30:00'
      },
      {
        id: 7,
        patientName: '周九',
        gender: '女',
        age: 41,
        phone: '13300133000',
        doctor: '李医生',
        status: 'in_treatment',
        archiveId: 'A20240215007',
        lastVisit: '2024-03-15',
        nextVisit: '2024-04-15',
        diagnosis: '牙齿不齐',
        treatment: '传统矫正器',
        createTime: '2024-02-15 10:10:00'
      },
      {
        id: 8,
        patientName: '吴十',
        gender: '男',
        age: 30,
        phone: '13200132000',
        doctor: '王医生',
        status: 'initial',
        archiveId: 'A20240220008',
        lastVisit: '2024-02-20',
        nextVisit: '2024-03-20',
        diagnosis: '智齿问题',
        treatment: '智齿拔除',
        createTime: '2024-02-20 09:00:00'
      },
      {
        id: 9,
        patientName: '郑十一',
        gender: '女',
        age: 27,
        phone: '13100131000',
        doctor: '张医生',
        status: 'in_treatment',
        archiveId: 'A20240225009',
        lastVisit: '2024-03-25',
        nextVisit: '2024-04-25',
        diagnosis: '牙龈炎',
        treatment: '牙龈治疗',
        createTime: '2024-02-25 14:00:00'
      },
      {
        id: 10,
        patientName: '王十二',
        gender: '男',
        age: 38,
        phone: '13000130000',
        doctor: '李医生',
        status: 'completed',
        archiveId: 'A20240301010',
        lastVisit: '2024-04-01',
        nextVisit: null,
        diagnosis: '牙髓炎',
        treatment: '根管治疗',
        createTime: '2024-03-01 11:30:00'
      }
    ]
    
    // 应用筛选条件
    let filteredData = [...allData]
    
    // 按关键词筛选（患者姓名或手机号）
    if (searchForm.keyword) {
      const keyword = searchForm.keyword.toLowerCase()
      filteredData = filteredData.filter(item => 
        item.patientName.toLowerCase().includes(keyword) || 
        item.phone.includes(keyword)
      )
    }
    
    // 按状态筛选
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    // 按日期范围筛选
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      const startDate = searchForm.dateRange[0].format('YYYY-MM-DD')
      const endDate = searchForm.dateRange[1].format('YYYY-MM-DD')
      
      filteredData = filteredData.filter(item => {
        const createDate = item.createTime.split(' ')[0]
        return createDate >= startDate && createDate <= endDate
      })
    }
    
    // 按档案号筛选
    if (searchForm.archiveId) {
      const archiveId = searchForm.archiveId.toLowerCase()
      filteredData = filteredData.filter(item => 
        item.archiveId.toLowerCase().includes(archiveId)
      )
    }
    
    // 更新表格数据和分页信息
    tableData.value = filteredData
    pagination.total = filteredData.length
    loading.value = false
  }, 500)
}

// 显示新建病例弹窗
const showNewCaseModal = () => {
  modalTitle.value = '新建病例'
  currentCase.value = null
  caseModalVisible.value = true
}

// 查看病例
const viewCase = (record) => {
  selectedCase.value = { ...record }
  
  // 根据病例ID加载相关数据
  loadCaseDetails(record.id)
  
  caseDetailVisible.value = true
}

// 加载病例详情相关数据
const loadCaseDetails = (caseId) => {
  // 模拟加载就诊记录
  visitRecords.value = generateVisitRecords(caseId)
  
  // 模拟加载影像资料
  caseImages.value = generateCaseImages(caseId)
  
  // 模拟加载处方记录
  prescriptions.value = generatePrescriptions(caseId)
}

// 从详情页面编辑
const handleEditFromDetail = () => {
  caseDetailVisible.value = false
  editCase(selectedCase.value)
}

// 编辑病例
const editCase = (record) => {
  modalTitle.value = '编辑病例'
  currentCase.value = { ...record }
  caseModalVisible.value = true
}

// 删除病例
const deleteCase = (record) => {
  // 实现删除病例的逻辑
  message.success('删除成功')
  fetchTableData()
}

// 处理病例表单提交
const handleCaseSubmit = (values) => {
  // 实现保存病例的逻辑
  console.log('save case', values)
  message.success('保存成功')
  caseModalVisible.value = false
  fetchTableData()
}

const router = useRouter()

// 处理退出登录
const handleLogout = () => {
  router.push('/login')
}

// 初始化加载数据
fetchTableData()

// 生成模拟就诊记录
const generateVisitRecords = (caseId) => {
  const records = []
  const count = Math.floor(Math.random() * 5) + 1  // 1-5条记录
  
  for (let i = 0; i < count; i++) {
    const date = new Date()
    date.setDate(date.getDate() - (i * 15))  // 每15天一次就诊
    
    records.push({
      date: date.toISOString().split('T')[0],
      doctor: ['李医生', '王医生', '张医生'][Math.floor(Math.random() * 3)],
      content: [
        '患者牙齿状况良好，继续按计划治疗。',
        '患者反映牙齿有轻微疼痛，已处理。',
        '治疗进展顺利，调整了治疗方案。',
        '完成了预定治疗项目，安排下次复诊。',
        '患者对治疗效果满意，无不适反应。'
      ][Math.floor(Math.random() * 5)]
    })
  }
  
  return records.sort((a, b) => new Date(b.date) - new Date(a.date))  // 按日期降序排列
}

// 生成模拟影像资料
const generateCaseImages = (caseId) => {
  const images = []
  const count = Math.floor(Math.random() * 4) + 2  // 2-5张图片
  
  const imageTypes = [
    { url: 'https://via.placeholder.com/300x200?text=X射线', description: 'X射线片' },
    { url: 'https://via.placeholder.com/300x200?text=口腔全景', description: '口腔全景片' },
    { url: 'https://via.placeholder.com/300x200?text=上颌', description: '上颌照片' },
    { url: 'https://via.placeholder.com/300x200?text=下颌', description: '下颌照片' },
    { url: 'https://via.placeholder.com/300x200?text=侧面', description: '侧面照片' }
  ]
  
  // 随机选择几种图片类型
  const selectedTypes = []
  while (selectedTypes.length < count) {
    const randomIndex = Math.floor(Math.random() * imageTypes.length)
    if (!selectedTypes.includes(randomIndex)) {
      selectedTypes.push(randomIndex)
    }
  }
  
  for (const index of selectedTypes) {
    images.push({
      ...imageTypes[index],
      date: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
    })
  }
  
  return images
}

// 生成模拟处方记录
const generatePrescriptions = (caseId) => {
  const prescriptions = []
  const count = Math.floor(Math.random() * 3) + 1  // 1-3条处方
  
  const medicineList = [
    { name: '氟化钠漱口液', dosage: '10ml', usage: '每日漱口2次' },
    { name: '牙周消炎凝胶', dosage: '适量', usage: '涂抹于患处，每日3次' },
    { name: '布洛芬片', dosage: '0.3g', usage: '疼痛时服用，每日不超过3次' },
    { name: '维生素C片', dosage: '1片', usage: '每日1次' },
    { name: '抗生素胶囊', dosage: '0.5g', usage: '每日3次，饭后服用' }
  ]
  
  for (let i = 0; i < count; i++) {
    const date = new Date()
    date.setDate(date.getDate() - (i * 10))  // 每10天一次处方
    
    // 随机选择2-3种药品
    const itemCount = Math.floor(Math.random() * 2) + 2
    const items = []
    const selectedIndices = new Set()
    
    while (items.length < itemCount) {
      const randomIndex = Math.floor(Math.random() * medicineList.length)
      if (!selectedIndices.has(randomIndex)) {
        selectedIndices.add(randomIndex)
        items.push(medicineList[randomIndex])
      }
    }
    
    prescriptions.push({
      date: date.toISOString().split('T')[0],
      doctor: ['李医生', '王医生', '张医生'][Math.floor(Math.random() * 3)],
      items,
      notes: [
        '按时服用，注意观察是否有不良反应',
        '如有不适请立即停药并联系医生',
        '治疗期间避免食用辛辣刺激性食物',
        '保持口腔卫生，每日刷牙不少于两次'
      ][Math.floor(Math.random() * 4)]
    })
  }
  
  return prescriptions.sort((a, b) => new Date(b.date) - new Date(a.date))  // 按日期降序排列
}
</script>

<style scoped>
.cases-layout {
  min-height: 100vh;
}

.content {
  padding-top: 64px; /* Space for fixed header */
  padding: 24px;
  background: #f0f2f5;
}

.page-header {
  background: #fff;
  padding: 16px 24px;
  border-radius: 4px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.page-content {
  background: #fff;
  padding: 24px;
  border-radius: 4px;
}

.search-bar {
  margin-bottom: 24px;
}

.danger-link {
  color: #ff4d4f;
}

.danger-link:hover {
  color: #ff7875;
}

.case-detail {
  padding: 24px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.patient-info {
  display: flex;
  align-items: center;
}

.patient-info h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.archive-id {
  margin-left: 16px;
  font-size: 14px;
  color: #666;
}

.detail-actions {
  display: flex;
  justify-content: flex-end;
}

.visit-records {
  padding: 24px;
}

.visit-record {
  padding: 16px;
  border-bottom: 1px solid #ddd;
}

.visit-record:last-child {
  border-bottom: none;
}

.visit-date {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}

.visit-doctor {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.visit-content {
  font-size: 14px;
  color: #666;
}

.image-gallery {
  padding: 24px;
}

.image-item {
  display: inline-block;
  margin: 16px;
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-description {
  font-size: 14px;
  color: #666;
  margin-top: 8px;
}

.image-date {
  font-size: 14px;
  color: #666;
  margin-top: 8px;
}

.prescription-detail {
  padding: 24px;
}

.prescription-doctor {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}

.prescription-items {
  margin-bottom: 16px;
}

.prescription-item {
  padding: 16px;
  border-bottom: 1px solid #ddd;
}

.prescription-item:last-child {
  border-bottom: none;
}

.item-name {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 8px;
}

.item-dosage {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.item-usage {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.prescription-notes {
  font-size: 14px;
  color: #666;
  margin-top: 16px;
}
</style>